<?php

class AccountConfiguration extends Configuration {
	protected $AppName = "account";
	protected $UseApps = array(array("name" => "smarty"), array("name" => "mysql"));
	protected $IncludeFiles = array("account.class.php");
	private $Admin;

	function registerMethods(AdminController $admin){
		$admin->register($this->AppName, "list", "listAccounts", $this->Language->get("display_accounts"));
		$admin->register($this->AppName, "edit", "editAccount", null);
	}

	function editAccount(){
		// get url position and read URL parameter
		$URLPosition = SystemRegistry::getInstance()->get("url_position");
		$HTTP = new HTTPRequest();

		$ID = $HTTP->get($URLPosition+3);

		// add some stylesheet
		$SmartyController = $this->UseApps["smarty"];
		$SmartyController->addHeadTag("<link rel=\"stylesheet\" type=\"text/css\" href=\"{\$env.url}lib/account/views/account.css\" />");

		// if parameter exists, display account
		if(is_numeric($ID)){
			$MySQL = $this->UseApps["mysql"];
			$SelectAccount = $MySQL->query("SELECT * FROM {$MySQL->getPrefix()}accounts WHERE id = $ID");

			if(mysql_num_rows($SelectAccount) != 1){
				return "Account with given ID doesn't exist.";
			}

			$Fetch = mysql_fetch_assoc($SelectAccount);

			$Account = new Account($MySQL, $Fetch["username"]);

			if(isset($_POST["editAccount"]) && !empty($_POST["access_layer"])){
				if(!is_numeric($_POST["access_layer"])){
					return "Cannot update - access layer must be numeric!";
				}
				$NewAccess = $_POST["access_layer"];

				if(!empty($_POST["password"])){
					$NewPassword = md5($_POST["password"]);
					if($Account->updateAccount($Account->getUsername(), $NewPassword, null, $NewAccess)){
						return "Successfully updated.";
					}
					else {
						return "Error updating.";
					}
				}
				else {
					if($Account->updateAccount($Account->getUsername(), null, null, $NewAccess)){
						return "Successfully updated.";
					}
					else {
						return "Error updating.";
					}
				}

			}

			$AccessLayers = $MySQL->query("SELECT * FROM {$MySQL->getPrefix()}access");

			$Layers = array();

			while ($layer = mysql_fetch_assoc($AccessLayers)) {
				$Layers[] = $layer;
			}

			$Smarty = $SmartyController->getSmarty();
			$Smarty->assign("account_cfg_account", $Account);
			$Smarty->assign("account_access_layers", $Layers);
		}

		$this->ViewFile = "config_account.tpl";
		return true;
	}

	function listAccounts(){
		$MySQL = $this->UseApps["mysql"];

		$SmartyController = $this->UseApps["smarty"];
		$Smarty = $SmartyController->getSmarty();

		$Accounts = array();

		$SelectAccounts = $MySQL->query("SELECT * FROM {$MySQL->getPrefix()}accounts ORDER BY id ASC");

		while ($acc = mysql_fetch_assoc($SelectAccounts)) {
			$Accounts[] = new Account($MySQL, $acc["username"]);
		}

		$this->ViewFile = "config_list.tpl";
		$Smarty->assign("account_cfg_acc_list", $Accounts);

		return true;
	}
}

?>